package org.example.baseinfo.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import io.micrometer.common.util.StringUtils;
import org.example.baseinfo.entity.SchoolEntity;
import org.example.baseinfo.pojo.vo.school.SchoolVO;
import org.example.baseinfo.repository.ISchoolRepository;
import org.example.baseinfo.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;


@Component
public class QueueMngListenter {



    @Autowired
    private ISchoolRepository schoolRepository;


    @Autowired
    private RedisUtil redisUtil;

    private Logger logger = LoggerFactory.getLogger(QueueMngListenter.class);


    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "school_change",durable="true",autoDelete = "false"),
            exchange = @Exchange(value = "baseInfo.school.exchange", type = ExchangeTypes.FANOUT), key = "school_base_change"))
    public void onMessage2(Message message, Channel channel) throws Exception {
        //消息获取并处理
        String jsonStr = new String(message.getBody(), "UTF-8");
        //获取路由key
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        if("school_base_change".equals(routingKey)){
            SchoolVO infoBo = JSON.parseObject(jsonStr, SchoolVO.class);
            //修改学员表中机构名称字段
            String s = redisUtil.get(infoBo.getSchoolId());
            SchoolEntity entity = null;
            if (StringUtils.isNotBlank(s))
                entity = JSON.parseObject(s,SchoolEntity.class);
            if (entity != null) {
                BeanUtils.copyProperties(infoBo, entity);
            }else {
                entity = schoolRepository.findByIdAndDeleteStatus(infoBo.getSchoolId(),Short.valueOf("1"));
            }
            redisUtil.del(infoBo.getSchoolId());
            schoolRepository.save(entity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            //清除对应缓存
            redisUtil.del(infoBo.getSchoolId());
        }else{
            //接收到的消息routingKey与设定的不一致，消息丢弃
            //接收到的消息routingKey与设定的不一致，消息丢弃
            logger.info("######教学修改机构信息MQ接收非正常数据= {}", jsonStr);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }



}
